package com.edu.controller.book;


import com.edu.dto.ResultDto;
import com.edu.entity.SearchEntity;
import com.edu.service.BookService;
import com.edu.service.impl.BookServiceImpl;
import com.edu.utils.ReturnCode;
import com.edu.utils.ServletHelper;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;


/**
 * com.edu.controller.book
 * 2024/7/13 23:20
 *
 * @author Fancy
 * @version 1.0
 */
@WebServlet("/books/search")
public class BooksSearchController extends HttpServlet {
    BookService bookService = new BookServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        // 获取搜索关键词
        //SearchEntity searchEntity = ServletHelper.getRequestBodyAsObject(req, SearchEntity.class);
        //使用getRequestBodyAsJson会出现中文乱码，但是使用getRequestBodyAsObject不会
        String search = req.getParameter("search");
        System.out.println("获取到search: " + search);

//        //解决办法，重点
//        BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream(),"UTF-8"));
//        StringBuilder sb = new StringBuilder("");
//        String line;
//        while ((line = reader.readLine()) != null) {
//            sb.append(line);
//        }
//        String result = sb.toString();
//        // 使用URLDecoder解码，解决中文乱码
//        //result = java.net.URLDecoder.decode(result, "UTF-8");
//        System.out.println(result);


        // 根据搜索关键词查询图书信息
        HashMap<String, Object> booksInfo = bookService.getBookInfoBySearch(search);

        if (booksInfo != null) {
            String rst = ResultDto.success(booksInfo);
            resp.setStatus(HttpServletResponse.SC_OK);
            resp.getWriter().write(rst);
        } else {
            String rst = ResultDto.fail(ReturnCode.UNAUTHORIZED.getCode(), "获取书籍信息失败。");
            resp.setStatus(HttpServletResponse.SC_OK);
            resp.getWriter().write(rst);
        }
    }
}
